package model

import (
	"novel-mgr1/userrpc/userrpc"

	"gorm.io/gorm"
)

type Novel struct {
	gorm.Model
	NovelTitle string `gorm:"type:varchar(30);not null"`
	NovelClass string `gorm:"type:varchar(30);not null"`
	NovelInfo  string `gorm:"type:varchar(30);not null"`
	Cid        int64  `gorm:"type:int;not null"`
}

func (n *Novel) NovelAdd(db *gorm.DB) error {
	return db.Debug().Create(n).Error
}

func (n *Novel) FindNovelById(db *gorm.DB, nid int64) error {
	return db.Debug().Where("id = ?", nid).Find(n).Error
}

func (n *Novel) NovelShow(db *gorm.DB, nid int64) userrpc.CommentListResponse {
	var list userrpc.CommentListResponse
	db.Debug().Model(&Novel{}).Select("users.id as uid,users.nickname as nick_name,novels.*").Joins("left join users on novels.cid = users.id").Where("novels.id=?", nid).First(&list)
	return list
}

func NovelList(db *gorm.DB, in *userrpc.NovelListRequest) ([]*userrpc.NovelList, int64) {
	var list []*userrpc.NovelList
	var count int64
	tx := db.Debug().Model(&Novel{}).Select("users.mobile,novels.*").Joins("left join users on users.id = novels.cid")
	if in.Types == 1 {
		tx.Order("novels.created_at desc")
	}

	if in.NovelTitle != "" {
		tx.Where("novels.novel_title like ?", "%"+in.NovelTitle+"%")
	}
	if in.NovelClass != "" {
		tx.Where("novels.novel_class like ?", "%"+in.NovelClass+"%")
	}

	tx.Count(&count)
	tx.Scopes(Paginate(int(in.Page), int(in.Size))).Find(&list)

	return list, count
}
